package com.simplefaith.delisty.client;

import static com.simplefaith.delisty.client.packet.opcode.ClientOpCodes.Sep;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.app.Activity;

import com.simplefaith.delisty.client.packet.manager.PacketManager;
import com.simplefaith.delisty.util.LocationDetector;
import com.simplefaith.delisty.util.StreamUtil;

public class ClientInstance extends Thread {

	private static ClientInstance instance;

	public static ClientInstance getClient() {
		if (instance == null)
			instance = new ClientInstance();
		return instance;
	}

	private static PacketManager packetManager;

	private final Socket client;
	private InputStream in;
	private OutputStream out;

	private BufferedReader br;
	private PrintWriter pw;

	private final InetSocketAddress isAddr;

	public ClientInstance() {
		client = new Socket();
		isAddr = new InetSocketAddress("118.163.94.4", 9000);

		packetManager = PacketManager.getInstance();

		this.start();
	}

	public ClientInstance(Socket client, InetSocketAddress isAddr) {
		this.client = client;
		this.isAddr = isAddr;

		packetManager = PacketManager.getInstance();

		this.start();
	}

	public void DisConnect() {
		try {
			// interrupt thread
			this.interrupt();
			// close socket
			client.close();
		} catch (Exception e) {

		}
		// close stream
		StreamUtil.close(br, pw, out, in);
	}

	@Override
	public void run() {

		try {
			client.connect(isAddr, 10000);
			in = client.getInputStream();
			out = client.getOutputStream();

			br = new BufferedReader(new InputStreamReader(in, "Unicode"));
			pw = new PrintWriter(new OutputStreamWriter(out, "Unicode"), true);

		} catch (IOException e) {
			System.out.println("Socket Problems Occurred");
			System.out.println("IOException: " + e.toString());
		}

		while (!this.client.isClosed()) {
			// do receive data and add to packet Queue

			try {

				String msg = br.readLine();

				String[] dataList = msg.split(Sep);
				int packetType = Integer.valueOf(dataList[0]);
				int packetSubype = Integer.valueOf(dataList[1]);

				System.out.println(msg);

				packetManager.getPacketTypeManager(packetType)
						.getPacketHandler(packetSubype).ReceivePacket(msg);

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public void sendClientPacket(String message) {
		try {
			pw.println(message);
		} catch (Exception e) {

		}
	}

}
